package com.lhd.qd.websocket;

import com.lhd.qd.common.consts.WsCodeEnum;
import com.lhd.qd.common.exception.AuthenticationException;
import com.lhd.qd.common.util.TokenUtils;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArraySet;

@ServerEndpoint(value = "/ws/{token}", encoders = { WsEncoder.class })
@Component
public class WebSocket {

    private Session session;
    private static CopyOnWriteArraySet<WebSocket> webSockets =new CopyOnWriteArraySet<>();
    private static ConcurrentHashMap<Long, Session> sessionPool = new ConcurrentHashMap<>();

    @OnOpen
    public void onOpen(Session session, @PathParam("token") String token) {
        Long id = TokenUtils.parse(token);
        if (id == null) {
            throw new AuthenticationException();
        }
        this.session = session;
        webSockets.add(this);
        sessionPool.put(id, session);
    }

    @OnClose
    public void onClose(@PathParam("token") String token) {
        webSockets.remove(this);
        Long id = TokenUtils.parse(token);
        if (id != null) {
            sessionPool.remove(id);
        }
    }

    @OnMessage
    public void onMessage(String message, Session session, @PathParam("token") String token) {

    }

    @OnError
    public void onError(Session session, Throwable error) {
        error.printStackTrace();
    }

    /**
     * 发给所有建立连接的终端
     * @param wsCodeEnum
     * @param <T>
     */
    public <T> void send(WsCodeEnum wsCodeEnum) {

        send(wsCodeEnum, null);
    }

    /**
     * 发给所有建立连接的终端
     * @param wsCodeEnum
     * @param data
     * @param <T>
     */
    public <T> void send(WsCodeEnum wsCodeEnum, T data) {

        for(WebSocket webSocket : webSockets) {
            try {
                webSocket.session.getAsyncRemote().sendObject(new WsResult<>(wsCodeEnum.getCode(), data));
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 发给某些人
     * @param wsCodeEnum
     * @param data
     * @param userIdList
     * @param <T>
     */
    public <T> void send(WsCodeEnum wsCodeEnum, T data, List<Long> userIdList) {

        for (Long userId : userIdList) {
            Session session = sessionPool.get(userId);
            if (session != null) {
                try {
                    session.getAsyncRemote().sendObject(new WsResult<>(wsCodeEnum.getCode(), data));
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
